<template>
  <div class="container">
    <el-divider content-position="left"><span class="title-left-color">用户基本信息</span></el-divider>
    <div style="margin: 0 70px">
      <el-descriptions :column="2" size="default">
        <el-descriptions-item label="昵称：">{{ form.nickname }}</el-descriptions-item>
        <el-descriptions-item label="手机号：">{{ form.mobile }}</el-descriptions-item>
        <el-descriptions-item label="余额：">{{ form.user_money }}</el-descriptions-item>
        <el-descriptions-item label="积分：">{{ form.pay_points }}</el-descriptions-item>
        <el-descriptions-item label="绑定店铺信息：" v-if="form.store.name !== ''">{{ form.store.name }},{{ form.store.mobile }}</el-descriptions-item>
      </el-descriptions>
    </div>
    <el-divider content-position="left"><span class="title-left-color">修改信息</span></el-divider>
    <el-form ref="formRef" :model="form" :rules="rules" v-loading="loading" label-width="150px">
      <el-row :gutter="10">
        <el-col :span="5">
          <el-form-item label="是否注销：" prop="is_cancellation">
            <el-radio-group v-model="form.is_cancellation">
              <el-radio label="1" :value="1">是</el-radio>
              <el-radio label="0" :value="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="是否冻结：" prop="is_lock">
            <el-radio-group v-model="form.is_lock">
              <el-radio label="1" :value="1">是</el-radio>
              <el-radio label="0" :value="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="footer-center">
      <el-button :disabled="disabledbtn" @click="cancelSubmit">取 消</el-button>
      <el-button type="primary" :disabled="disabledbtn" v-if="!isDisabledbtn" @click="submitForm">确 定</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { postOrPutType } from "@/constants";
import type { HasId, ViewMode } from "@/types/common";
import type { IUserDTO, IUserInfo, IUserVO } from "@/types/user";
import { commonAppUserInfo, getAppUserByIdInfo } from "@/utils/api/user";
import { useState } from "@/hooks/useState.ts";
const { disabledbtn, loading, toggleState } = useState();
interface Props {
  id: number;
}
const { id } = defineProps<Props>();
const formStatus = defineModel<ViewMode>("formStatus", { required: true });
const emit = defineEmits<{
  handleInitData: [];
  handleSuccess: [];
}>();

const isDisabledbtn = ref(false);
const formRef = useTemplateRef("formRef");
const methodType = ref<postOrPutType>("PUT");
const form = reactive<IUserVO>({
  nickname: "",
  user_money: "",
  pay_points: "",
  mobile: "",
  reg_time: 0,
  is_lock: 0,
  is_distribut: 0,
  is_cancellation: 0,
  store: {
    mobile: "",
    name: ""
  }
});

const formData = reactive<IUserDTO>({
  id: 0,
  is_lock: 0,
  is_cancellation: 0
});

const rules = reactive({
  is_cancellation: [{ required: true, message: "请选择账户注销状态", trigger: "blur" }],
  is_lock: [{ required: true, message: "请选择账号冻结状态", trigger: "blur" }]
});

// const emit = defineEmits([]);
// Lifecycle hooks
onMounted(() => {
  console.log("Component mounted!");
});

/* formStatus处理器 */
const statusHandlers: Record<ViewMode, () => void> = {
  view: () => {
    isDisabledbtn.value = true;
  },
  edit: () => {
    methodType.value = "PUT";
  },
  add: () => {
    methodType.value = "POST";
  },
  none: () => {
    /* 初始化数据 */
    handleInitData();
  }
};
/* 监听formStatus,新增，编辑，查看的时候都可以打开模态框，又是有不同的操作和效果，需要单独判断，none为模态框关闭的情况，需要初始化数据 */
watch(formStatus, newValue => {
  const handler = statusHandlers[newValue];
  handler?.();
});
/*  */
watch(
  () => id,
  newValue => {
    if (newValue == 0) {
      /* 初始化数据 */
    } else {
      formData.id = newValue;
      handleGetAppUserByIdInfo(id);
    }
  }
);

/* 初始化数据 */
function handleInitData() {
  methodType.value = "POST";
  isDisabledbtn.value = false;

  formData.id = 0;
  formData.is_cancellation = 0;
  formData.is_lock = 0;
  formRef.value?.resetFields();
  formRef.value?.clearValidate();

  form.nickname = "";
  form.user_money = "";
  form.pay_points = "";
  form.mobile = "";
  form.reg_time = 0;
  form.is_lock = 0;
  form.is_distribut = 0;
  form.is_cancellation = 0;
  form.store.mobile = "";
  form.store.name = "";
}

/* 通过id获取前端账户详情信息 */
function handleGetAppUserByIdInfo(id: number) {
  getAppUserByIdInfo<IUserInfo, HasId>({ id })
    .then(res => {
      form.nickname = res.result.nickname;
      form.user_money = res.result.user_money;
      form.pay_points = res.result.pay_points;
      form.mobile = res.result.mobile;
      form.reg_time = res.result.reg_time;
      if (res.result.store) {
        form.store.mobile = res.result.store.mobile;
        form.store.name = res.result.store.name;
      }
      form.is_cancellation = res.result.is_cancellation;
      form.is_lock = res.result.is_lock;
    })
    .catch(res => {
      console.log(res);
      //this.$message.error("服务器繁忙，请稍后再试");
    });
}

/* 保存或编辑 */
function submitForm() {
  if (!formRef.value) return;
  formRef.value.validate(valid => {
    if (!valid) {
      ElMessage.warning("请填写必填字段");
      return;
    }
    formData.is_cancellation = form.is_cancellation;
    formData.is_lock = form.is_lock;
    submitFormInfo();
  });
}

/* 保存或编辑信息 */
function submitFormInfo() {
  /* 防止多次提交 */
  toggleState(true);
  commonAppUserInfo(formData, methodType.value)
    .then(res => {
      ElMessage.success(res.msg);
      cancelSubmit();
      emit("handleSuccess");
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 保存或编辑 取消提交 */
function cancelSubmit() {
  // clearData();
  // activeName = "one";
  emit("handleInitData");
}
</script>

<style lang="scss" scoped>
/* 底部按钮居中 */
.footer-center {
  margin: 10px 0;
  text-align: center;
}
</style>
